package com.online.music.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.online.music.entity.dto.AlbumAddSongsDTO;
import com.online.music.entity.po.Album;
import com.online.music.entity.po.Song;
import com.online.music.exception.BaseException;
import com.online.music.mapper.AlbumMapper;
import com.online.music.mapper.SongMapper;
import com.online.music.service.IAlbumService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.online.music.utils.UserContextUtil;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Set;

import com.online.music.common.Result;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Leno
 * @Date: 2025-01-31
 * @Description: AlbumServiceImpl
 */
@Service
@RequiredArgsConstructor
public class AlbumServiceImpl extends ServiceImpl<AlbumMapper, Album> implements IAlbumService {

    private final AlbumMapper albumMapper;

    private final SongMapper songMapper;

    @Override
    public Result<Page<Album>> findPage(Integer pageNum, Integer pageSize, Album album) {
        Page<Album> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Album> lqw = new LambdaQueryWrapper<>();
        // 添加条件...
        if (StrUtil.isNotBlank(album.getName())) {
            lqw.like(Album::getName, album.getName());
        }
        if (album.getUserId() != null) {
            lqw.eq(Album::getUserId, album.getUserId());
        }

        return Result.success(page(page, lqw));
    }

    @Override
    @Transactional
    public Result<String> deleteBatch(List<Long> ids) {
        // 删除前先判断是否存在...
        removeByIds(ids);
        // 同时删除关联的歌曲
        songMapper.update(
                new LambdaUpdateWrapper<Song>()
                        .set(Song::getAlbumId, null)
                        .in(Song::getAlbumId, ids)
        );
        return Result.successMsg("删除成功");
    }

    @Override
    public Result<String> addSong(AlbumAddSongsDTO albumAddSongsDTO) {
        // 先检查专辑是否存在
        Album album = albumMapper.selectById(albumAddSongsDTO.getId());
        if (album == null) {
            return Result.error("专辑不存在");
        }

        // 再检查歌曲是否存在
        Set<Long> songIds = albumAddSongsDTO.getSongIds();
        Long count = songMapper.selectCount(
                new LambdaQueryWrapper<Song>()
                        .in(Song::getId, songIds)
        );
        if (count != songIds.size()) {
            return Result.error("有歌曲不存在");
        }

        // 添加歌曲到专辑
        // 就是修改歌曲的专辑id
        // 先检查歌曲是否已经有专辑关联，如果有就不允许添加，并且用户只能操作自己创建的歌曲到专辑中
        Long albumCount = songMapper.selectCount(
                new LambdaQueryWrapper<Song>()
                        .select(Song::getAlbumId)
                        .in(Song::getId, songIds)
        );
        if (albumCount > 0) {
            return Result.error("有歌曲已经有专辑关联");
        }

        // 查询将要添加进来的歌曲信息
        List<Song> addSongs = songMapper.selectList(
                new LambdaQueryWrapper<Song>()
                        .select(Song::getArtist)
                        .in(Song::getId, songIds)

        );

        // 先检查添加里面的歌曲的歌手是否一致
        String addArtist = addSongs.get(0).getArtist();
        addSongs.forEach(song -> {
            if (!song.getArtist().equals(addArtist)) {
                throw new BaseException("歌手必须一致");
            }
        });

        // 查询专辑中已有的歌曲信息
        List<Song> songs = songMapper.selectList(
                new LambdaQueryWrapper<Song>()
                        .select(Song::getArtist)
                        .eq(Song::getAlbumId, albumAddSongsDTO.getId())
        );

        // 如果专辑中有歌曲
        if (!songs.isEmpty()) {
            String artist = songs.get(0).getArtist();

            addSongs.forEach(song -> {
                // 查询将要添加进来的歌曲的歌手是否一致
                if (!song.getArtist().equals(artist)) {
                    throw new BaseException("歌手必须一致");
                }
            });
        }


        // 批量更新歌曲的专辑id
        songMapper.update(
                new LambdaUpdateWrapper<Song>()
                        .set(Song::getAlbumId, albumAddSongsDTO.getId())
                        .in(Song::getId, songIds)
        );


        return Result.successMsg("添加成功");
    }

    @Override
    public Result<String> removeSong(AlbumAddSongsDTO albumAddSongsDTO) {
        // 删除关联
        songMapper.update(
                new LambdaUpdateWrapper<Song>()
                        .set(Song::getAlbumId, null)
                        .eq(Song::getAlbumId, albumAddSongsDTO.getId())
                        .in(Song::getId, albumAddSongsDTO.getSongIds())
        );
        return Result.successMsg("删除成功");
    }

    @Override
    public Result<List<Song>> getAvailableSongs() {
        // 获取专辑可用的歌曲
        // 已审核通过的歌曲，且专辑id为空
        List<Song> songs = songMapper.selectList(
                new LambdaQueryWrapper<Song>()
                        .eq(Song::getUserId, UserContextUtil.getUserId())
                        .eq(Song::getStatus, 1)
                        .isNull(Song::getAlbumId)
        );
        return Result.success(songs);
    }

    @Override
    public Result<List<Song>> getAlbumSongs(Long id) {
        List<Song> songs = songMapper.selectList(
                new LambdaQueryWrapper<Song>()
                        .eq(Song::getAlbumId, id)
        );
        return Result.success(songs);
    }

}

